import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import { loginApi, getAdminInfoApi, getMenuRoutesApi, getPermissionsApi } from '@/api/auth';
import { getConfigApi } from "@/api/sysConfig";
import { RouteRecordRaw } from 'vue-router';
import { useWebSocketStore } from "@/stores/websocket";
import { useRouteStore } from '@/stores/route';

export const useAuthStore = <any>defineStore('auth', () => {
    // 系统设置
    const system = ref(JSON.parse(localStorage.getItem('system') || null));
    // 从 localStorage 初始化 token
    const token = ref<string | null>(localStorage.getItem('token') || null);
    // 路由菜单
    const routes = ref<RouteRecordRaw[]>(JSON.parse(localStorage.getItem('routes') || '[]')); // 存储后端返回的路由
    // 用户信息
    const userInfo = ref(JSON.parse(localStorage.getItem('userInfo') || null));
    // 权限列表
    const permissions = ref<string[]>(JSON.parse(localStorage.getItem('permissions') || '[]'));
    // 是否已经加载了路由
    const isDynamicRoutesLoaded = ref(false);
    // 是否已经登陆
    const isAuthenticated = computed(() => token.value !== null);

    // 登录方法
    const login = async (data: any) => {
        try {
            const response = await loginApi(data);
            if (response.data.token) {
                token.value = response.data.token; // 注意这里应该是 response.data.token 而不是 response.token
                localStorage.setItem('token', response.data.token); // 保存 Token 到 localStorage
                // const wsStore = useWebSocketStore()
                // wsStore.send('LOGIN', { login_token: token.value });
                await getAdminInfo() // 登录成功后获取用户信息
                await getMenuRoutes() // 菜单路由
                await getPermissions() // 权限标识列表
                await getSystem() // 系统设置
            }
        } catch (error) {
            throw error;
        }
    };

    // 获取用户信息
    const getAdminInfo = async () => {
        try {
            const response = await getAdminInfoApi();
            if(response.data) {
                userInfo.value = response.data;
                // 保存 用户信息 到 localStorage
                localStorage.setItem('userInfo', JSON.stringify(response.data));
            }
        } catch (error) {
            throw error;
        }
    };

    // 获取菜单路由信息
    const getMenuRoutes = async () => {
        try {
            const response = await getMenuRoutesApi();
            if(response.data) {
                routes.value = response.data;
                // 保存 路由菜单 到 localStorage
                localStorage.setItem('routes', JSON.stringify(response.data));
            }
        } catch (error) {
            throw error;
        }
    };

    // 获取权限标识列表
    const getPermissions = async () => {
        try {
            const response = await getPermissionsApi();
            if(response.data) {
                permissions.value = response.data;
                // 保存 权限列表 到 localStorage
                localStorage.setItem('permissions', JSON.stringify(response.data));
            }
        } catch (error) {
            throw error;
        }
    };

    // 权限验证
    const hasPermission = (permission: string | string[]) => {
        if(Array.isArray(permission)) {
            return permission.some(p => permissions.value.includes(p));
        }
        return permissions.value.includes(permission as string);
    }

    // 退出登录
    const logout = () => {
        token.value = null;
        userInfo.value = null;
        routes.value = [];
        permissions.value = [];

        // 删除 tabs
        const routeStore = useRouteStore();
        routeStore.tabs = [{ title: '仪表盘', path: '/dashboard' }]
        localStorage.removeItem('routeTabs');

        // 清除 localStorage 中的相关数据
        localStorage.removeItem('token');
        localStorage.removeItem('userInfo');
        localStorage.removeItem('routes');
        localStorage.removeItem('permissions');
    };

    // 设置路由加载状态
    const setDynamicRoutesLoaded = (value: boolean) => {
        isDynamicRoutesLoaded.value = value;
    };

    // 设置系统配置
    const setSystem = (value: string | string[]) => {
        system.value = value
        localStorage.setItem('system', JSON.stringify(value));
    };

    // 获取系统配置
    const getSystem = async () => {
        await getConfigApi('system_config').then(res => {
            setSystem(res.data)
        })
        return system.value
    }

    return {
        system,
        token,
        routes,
        userInfo,
        isDynamicRoutesLoaded,
        isAuthenticated,
        login,
        logout,
        getMenuRoutes,
        getPermissions,
        hasPermission,
        getAdminInfo,
        setDynamicRoutesLoaded,
        setSystem,
    };
});